//
//  PersonalController.m
//  HuiPinZhiJia
//
//  Created by MS on 16/9/8.
//  Copyright © 2016年 MS. All rights reserved.
//

#import "PersonalController.h"
#import "UIImageView+WebCache.h"
#import "AFNetworkReachabilityManager.h"
#import "AppDelegate.h"
@interface PersonalController ()<UITableViewDataSource,UITableViewDelegate,UIImagePickerControllerDelegate>
@property (nonatomic,strong)NSMutableArray *dataSource;
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *netSourece;
@property (nonatomic,strong)UIImagePickerController *Picker;
@property (nonatomic,strong)UIImageView *imageView;
@end

@implementation PersonalController

- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
    [self.tableView reloadData];

}
- (void)viewWillDisappear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _Picker = [[UIImagePickerController alloc]init];
    _Picker.delegate = (id)self;
    _Picker.editing = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    _dataSource = [[NSMutableArray alloc]initWithObjects:@"头像",@"昵称",@"性别",@"账户安全",@"邮箱",@"验证密码",@"实名认证",nil];
   
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 60, screenWidth, screenHeight - 66) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource =self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.bounces = NO;
    [self.view addSubview:_tableView];
    
    [self createSource];

}
//*avatar,*nickname,*sex,*mobile,*email,*salt;//头像，昵称,性别，手机号，邮箱,积分

//构建netSource数组
-(void)createSource
{
    _netSourece = [[NSMutableArray alloc]init];
    [_netSourece addObject:@""];
    NSString *nickname = _model.nickname;
    nickname = [nickname isEqualToString:@""]?@"匿名":nickname;
    [_netSourece addObject:nickname];
    
    NSString *sex = _model.sex;
    if ([sex isEqualToString:@"0"])
    {
        sex = @"保密";
    }else if([sex isEqualToString:@"1"])
    {
    sex = @"男";
    }else
    {
    sex = @"女";
    }
    [_netSourece addObject:sex];
    
    NSString *mobel = _model.mobile;
    mobel = [mobel isEqualToString:@""]?@"未绑定":mobel;
    [_netSourece addObject:mobel];
    
    NSString *emil = _model.email;
    emil = [emil isEqualToString:@""]?@"未绑定":emil;
    [_netSourece addObject:emil];
    
    [_netSourece addObject:@""];
    
    NSString *shim = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"is_certification"]];
    if ([shim isEqualToString:@"0"]) {
        shim = @"未实名认证";
    }else if ([shim isEqualToString:@"1"]){
        shim = @"已认证";
    }else{
        shim = @"审核中";
    }
    [_netSourece addObject:shim];
    
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"personalCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
    }
    cell.textLabel.text = _dataSource[indexPath.row];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    if (indexPath.row == 0) {
        _imageView = [[UIImageView alloc]initWithFrame:CGRectMake(screenWidth*2.8/4, 10, 90, 80)];
        [_imageView sd_setImageWithURL:[NSURL URLWithString:_url] placeholderImage:[UIImage imageNamed:@"头像"]];
        [_imageView.layer setCornerRadius:100];
        [cell addSubview:_imageView];
    }
    if (indexPath.row != 0) {
        cell.detailTextLabel.text = _netSourece[indexPath.row];
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 100;
    }
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"选择照片" message:@"从相册获取或拍照" preferredStyle:UIAlertControllerStyleActionSheet];
        [alert addAction:[UIAlertAction actionWithTitle:@"相册获取" style:UIAlertActionStyleDefault  handler:^(UIAlertAction * _Nonnull action) {
            UIImagePickerControllerSourceType sourceType =
            UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            _Picker.sourceType = sourceType;
            [self presentViewController:_Picker animated:YES completion:nil];
            
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault  handler:^(UIAlertAction * _Nonnull action) {
            UIImagePickerControllerSourceType sourceType =
            UIImagePickerControllerSourceTypeCamera;
            if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            }
            _Picker.sourceType = sourceType;
            [self presentViewController:_Picker animated:YES completion:nil];

        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
           
        }]];
        [self presentViewController:alert animated:YES completion:nil];

    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [_Picker dismissViewControllerAnimated:YES completion:nil];
    __weak typeof(self) weakSelf = self;
//上传头像
   if ([AFNetworkReachabilityManager sharedManager].isReachable)
    {
        [(AppDelegate *)[UIApplication sharedApplication].delegate NetState];
    }else
    {
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSString *token = [userDefaults objectForKey:@"token"];
        
        [[NetWorking sharedManager] postParameters:@{@"token":token} type:[NetWorking sharedManager].uploadImage ImageData:UIImageJPEGRepresentation(image,0.5) Name:@"file" progressValue:^(double value){
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
        }success:^(id info){
            if ([info[@"status"] integerValue] == 1) {
                NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
                [userDefaults setObject:info[@"data"] forKey:@"头像"];
                
                [userDefaults synchronize];
                //设置会员资料的会员图像
                 
            } else {
                MBProgressHUD * HUD=[(AppDelegate *)[UIApplication sharedApplication].delegate responseWithString:info[@"info"]];
                [HUD hide:YES afterDelay:0.7];
            }
        }failure:^(id error){
            MBProgressHUD * HUD=[(AppDelegate *)[UIApplication sharedApplication].delegate responseWithString:@"未知错误!"];
            [HUD hide:YES afterDelay:0.7];
        }];
    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
